﻿using System;
using System.Diagnostics;
using System.Windows;
using UIExceptionHandler;
using UIExceptionHandler.Controllers;

namespace UIExceptionHandlerWPF
{
    public static class UIException
    {
        public static void Start(string serverSmtp, int portSmtp, string passwdSmtp, string userSmtp, string programmerEmail, string fromEmail, string exceptionSubject)
        {
            Settings.ServerSMTP = serverSmtp;
            Settings.PortSMTP = portSmtp;
            Settings.PasswdSMTP = passwdSmtp;
            Settings.UserSMTP = userSmtp;
            Settings.ProgrammerEmail = programmerEmail;
            Settings.FromEmail = fromEmail;
            Settings.ExceptionSubject = exceptionSubject;

            try
            {
                LogHelper.SetupLogger();
            }
            catch (Exception e)
            {
                MessageBox.Show("Error work with logger!\n Send to developer" + e.Message);
                if (MessageBox.Show("Attach debugger? \n Only for developer!!!", "Debugging...", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    Debugger.Launch();
                    throw;
                }
            }

            AppDomain.CurrentDomain.UnhandledException += (sender, e) => HandleError((Exception)e.ExceptionObject);
        }

        private static void SetExceptionFilename(string name)
        {
            LogHelper.ExceptionLogFileName = name;
        }

        private static void HandleError(Exception exception)
        {
            try
            {
                new ErrorHandlerController(exception, new ErrorHandlerForm()).Run();
            }
            catch (Exception e)
            {

                LogHelper.Logger.Error(e);
                MessageBox.Show("Error processing exception. Please send log file " + LogHelper.ExceptionLogFileName + " to developer: " + Settings.ProgrammerEmail + " \r\n Exception:" + e);
                if (MessageBox.Show("Attach debugger? \n Only for developer!!!", "Debugging...", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    Debugger.Launch();
                    throw;
                }
            }
            finally
            {
                Environment.Exit(1);
            }
        }
    }
}
